package com.gin.kotlin.no_gay_alliance.store

import com.gin.kotlin.no_gay_alliance.base.DelegateDataStore
import com.gin.kotlin.no_gay_alliance.base.NamedDataStore
import com.gin.kotlin.no_gay_alliance.enums.NgaTheme
import com.gin.kotlin.no_gay_alliance.model.emoji.GenericEmojiGroup
import com.gin.nga.enums.NgaDomain
import java.lang.ref.WeakReference

/**
 * 全局配置
 */
class GlobalProperty private constructor() {
    private val dataStore = NamedDataStore.getInstance(javaClass.simpleName)

    /**
     * 当前使用的域名
     */
    var domain: NgaDomain
        get() = dataStore.get(KEY_DOMAIN, NgaDomain.MASTER.host).let { NgaDomain.find(it) } ?: NgaDomain.MASTER
        set(value) {
            dataStore.set(KEY_DOMAIN, value.host)
        }

    /**
     * 当前主题
     */
    var theme: NgaTheme
        get() = dataStore.get(KEY_THEME_CURRENT, NgaTheme.YELLOW.ordinal).let { NgaTheme.entries.first { e -> e.ordinal == it } }
        set(value) {
            dataStore.set(KEY_THEME_CURRENT, value.ordinal)
        }

    /**
     * 深色模式是否跟随系统
     */
    var themeFollow by DelegateDataStore(false, KEY_THEME_FOLLOW_SYSTEM)

    /**
     * 点按主题时，如果有浏览历史，是否直接打开该页
     */
    var openHistoryPage by DelegateDataStore(true, KEY_OPEN_HISTORY_PAGE)

    /**
     * 长按主题时，打开弹窗，或打开最后一页
     */
    var showPagerDialog by DelegateDataStore(false, KEY_SHOW_PAGER_DIALOG)

    /**
     * 是否自动为长回复添加引用框
     */
    var autoQuoteContent by DelegateDataStore(true)

    /**
     * 隐藏的表情包名称
     */
    var hiddenGenericEmojiGroup: HashSet<String>
        get() = dataStore.get(GenericEmojiGroup::class.java.simpleName, setOf<String>()).toHashSet()
        set(value) {
            dataStore.set(GenericEmojiGroup::class.java.simpleName, value)
        }

    companion object {
        const val KEY_DOMAIN = "DOMAIN"
        const val KEY_THEME_CURRENT = "THEME_CURRENT"
        const val KEY_THEME_FOLLOW_SYSTEM = "THEME_FOLLOW_SYSTEM"
        const val KEY_OPEN_HISTORY_PAGE = "OPEN_HISTORY_PAGE"
        const val KEY_SHOW_PAGER_DIALOG = "SHOW_PAGER_DIALOG"

        private val TAG = GlobalProperty::class.java.simpleName
        private var instance: WeakReference<GlobalProperty> = WeakReference(GlobalProperty())

        /**
         * 单例模式+弱引用
         * @return Any
         */
        fun getInstance(): GlobalProperty = instance.get() ?: GlobalProperty().also { instance = WeakReference(it) }
    }
}